﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure;
using DormMS.IService;
using DormMS.Model;
using Infrastructure.Dao;
using SqlSugar;
using Senparc.Weixin.MP.CommonAPIs;
using Infrastructure.Pub;

namespace DormMS.Service
{
    public class WxConfigService : IWxConfigService
    {
        public WxConfig GetConfig()
        {
            var model = BaseService.LoadEntity<WxConfig>(m => !m.IsDeleted);
            if (model == null || model.Id == 0)
            {
                var Id = BaseService.AddEntityByIdentity(new WxConfig { });
                return BaseService.LoadEntity<WxConfig>(m => m.Id == Id);
            }
            return model;
        }

        public Result WxConfigSubmit(WxConfig wxconfig)
        {
            return BaseService.UpdateEntity(wxconfig) ? Result.Success() : Result.Failure("保存失败");
        }


        /// <summary>
        /// 将token更新数据库
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public bool SaveToken(string token)
        {
            using (var db = DbConfig.GetInstance())
            {
                return db.Update<WxConfig>(new { AccessToken = token }, w => true);
            }
        }

        /// <summary>
        /// 获取有效的AccessToken
        /// </summary>
        /// <param name="url">用来请求微信验证token有效性的URL</param>
        /// <param name="appId"></param>
        /// <param name="secret"></param>
        /// <returns></returns>
        public string GetCurrentToken(string url, string appId, string secret)
        {
            try
            {
                var config = new WxConfig();
                string token = "";
                using (var db = DbConfig.GetInstance())
                {
                    config = db.Queryable<WxConfig>().Where(c=>c.IsDeleted==false).FirstOrDefault();
                    if (config != null && !string.IsNullOrWhiteSpace(config.AccessToken))
                    {
                        token = config.AccessToken;
                    }
                }
                //如果token此时为空，则直接调用SP的GetToken方法，并更新数据库,如果数据库中并没有config实体类，则每次都重新获取
                if (string.IsNullOrWhiteSpace(token))
                {
                    token = CommonApi.GetToken(appId, secret).access_token;
                    SaveToken(token);
                    return token;
                }
                //若token有值，则验证有效性，通过则直接return,不通过则重新申请
                string url2 = string.Format(url, token);
                string resultStr = new WebUtils().DoGet(url2, null);
                if (resultStr.IndexOf("40001") >= 0 || resultStr.IndexOf("42001") >= 0)
                {
                    token = CommonApi.GetToken(appId, secret).access_token;
                    SaveToken(token);
                }
                return token;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
